<template>
  <div class="search-form">
    <el-form
      :model="searchParams"
      ref="searchFormRef"
      label-width="100px"
      class="search-form-container"
      :label-position="isPhone ? 'top' : 'left'"
    >
      <el-row :gutter="20">
        <!-- 年级 -->
        <el-col :span="spanWidth">
          <el-form-item label="年级" prop="trainYear">
            <el-select
              v-model="searchParams.trainYear"
              placeholder="请选择年级"
              multiple
              clearable
              filterable
              style="width: 100%"
              collapse-tags
              collapse-tags-tooltip
              @change="val => handleChange(val, 'trainYear', yearOptions)"
              @blur="handleChangeBlur('trainYear', yearOptions)"
            >
              <el-option label="全部" value="" />
              <el-option
                v-for="year in yearOptions"
                :key="year.value"
                :label="year.label"
                :value="year.value"
              />
            </el-select>
          </el-form-item>
        </el-col>

        <!-- 高校 -->
        <el-col :span="spanWidth">
          <el-form-item label="高校" prop="trainUniversity">
            <el-select
              v-model="searchParams.trainUniversity"
              placeholder="请选择高校"
              multiple
              clearable
              filterable
              style="width: 100%"
              collapse-tags
              collapse-tags-tooltip
              @change="
                (val) => handleChange(val, 'trainUniversity', university)
              "
              @blur="handleChangeBlur('trainUniversity', university)"
            >
              <el-option label="全部" value="" />
              <el-option
                v-for="dict in university"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>
        </el-col>

        <!-- 培养单位 -->
        <el-col :span="spanWidth">
          <el-form-item label="培养单位" prop="trainDeptId">
            <el-select
              v-model="searchParams.trainDeptId"
              placeholder="请选择培养单位"
              multiple
              clearable
              filterable
              style="width: 100%"
              collapse-tags
              collapse-tags-tooltip
              @change="
                (val) => handleChange(val, 'trainDeptId', trainingUnitList)
              "
              @blur="handleChangeBlur('trainDeptId', trainingUnitList)"
            >
              <el-option label="全部" value="" />
              <el-option
                v-for="dept in trainingUnitList"
                :key="dept.deptId"
                :label="dept.deptName"
                :value="dept.deptId"
              />
            </el-select>
          </el-form-item>
        </el-col>

        <!-- 培养类型 -->
        <el-col :span="spanWidth">
          <el-form-item label="培养类型" prop="trainType">
            <el-select
              v-model="searchParams.trainType"
              placeholder="请选择培养类型"
              multiple
              clearable
              filterable
              style="width: 100%"
              collapse-tags
              collapse-tags-tooltip
              @change="
                (val) => handleChange(val, 'trainType', training_category)
              "
              @blur="handleChangeBlur('trainType', training_category)"
            >
              <el-option label="全部" value="" />
              <el-option
                v-for="dict in training_category"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>
        </el-col>

        <!-- 专业领域 -->
        <el-col :span="spanWidth">
          <el-form-item label="专业领域" prop="trainField">
            <el-select
              v-model="searchParams.trainField"
              placeholder="请选择专业领域"
              multiple
              clearable
              filterable
              style="width: 100%"
              collapse-tags
              collapse-tags-tooltip
              @change="(val) => handleChange(val, 'trainField', specialty)"
              @blur="handleChangeBlur('trainField', specialty)"
            >
              <el-option label="全部" value="" />
              <el-option
                v-for="dict in specialty"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>
        </el-col>

        <!-- 培养阶段 -->
        <el-col :span="spanWidth">
          <el-form-item label="培养阶段" prop="trainStatus">
            <el-select
              v-model="searchParams.trainStatus"
              placeholder="请选择培养阶段"
              multiple
              clearable
              filterable
              style="width: 100%"
              collapse-tags
              collapse-tags-tooltip
              @change="
                (val) => handleChange(val, 'trainStatus', train_progress)
              "
              @blur="handleChangeBlur('trainStatus', train_progress)"
            >
              <el-option label="全部" value="" />
              <el-option
                v-for="dict in train_progress"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>
        </el-col>

        <!-- 学生姓名 -->
        <el-col :span="spanWidth" v-if="!props.hideStudent">
          <el-form-item label="学生姓名" prop="userName">
            <el-input
              v-model="searchParams.userName"
              placeholder="请输入学生姓名"
              clearable
              style="width: 100%"
              @keyup.enter="handleSearch"
            />
          </el-form-item>
        </el-col>

        <!-- 毕业留企情况 -->
        <el-col :span="spanWidth">
          <el-form-item label="毕业留企情况" prop="graduateStay">
            <el-select
              v-model="searchParams.graduateStay"
              placeholder="请选择毕业留企情况"
              multiple
              clearable
              style="width: 100%"
              collapse-tags
              collapse-tags-tooltip
              @change="(val) => handleChange(val, 'graduateStay', sys_yes_no)"
              @blur="handleChangeBlur('graduateStay', sys_yes_no)"
            >
              <el-option label="全部" value="" />
              <el-option
                v-for="dict in sys_yes_no"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="isPhone ? 24 : 8" class="search-buttons">
          <el-form-item>
            <el-button type="primary" icon="Search" @click="handleSearch">
              搜索
            </el-button>
            <el-button icon="Refresh" @click="handleReset"> 重置 </el-button>
            <el-button
              v-if="showExport"
              type="primary"
              icon="Download"
              @click="handleExport"
            >
              导出
            </el-button>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
  </div>
</template>

<script setup name="SearchForm">
import { ref, reactive, computed, onMounted } from "vue";
import {
  getGradeDropdown,
  getUniversityDropdown,
  getTrainDeptDropdown,
  getTrainTypeDropdown,
  getTrainFieldDropdown,
  getTrainStatusDropdown,
  getGraduateStayDropdown,
} from "@/api/common";
import { isPhone } from "@/utils/index";

// Props
const props = defineProps({
  hideStudent: {
    type: Boolean,
    default: false,
  },
  // 初始搜索参数
  modelValue: {
    type: Object,
    default: () => ({}),
  },
  showExport: {
    type: Boolean,
    default: false,
  },
  exportFileName: {
    type: String,
    default: "",
  },
});

const spanWidth = computed(() => {
  return isPhone ? 12 : 8;
});

// Emits
const emit = defineEmits(["update:modelValue", "search", "reset"]);

// 获取代理对象
const { proxy } = getCurrentInstance();

// 从接口获取的选项数据
const yearOptions = ref([]);
const university = ref([]);
const training_category = ref([]);
const specialty = ref([]);
const train_progress = ref([]);
const sys_yes_no = ref([]);

// 表单引用
const searchFormRef = ref();

// 培养单位列表
const trainingUnitList = ref([]);

// 搜索参数
const searchParams = reactive({
  trainYear: [""], // 年级
  trainUniversity: [""], // 高校
  trainDeptId: [""], // 培养单位
  trainType: [""], // 培养类别
  trainField: [""], // 专业领域
  trainStatus: [""], // 培养阶段
  userName: "", // 学生姓名
  graduateStay: [""], // 是否留企
});

const filterParams = () => {
  // 过滤掉空值和"全部"选项
  const filteredParams = {};
  Object.keys(searchParams).forEach((key) => {
    const value = searchParams[key];
    if (Array.isArray(value)) {
      // 多选字段，过滤掉空字符串
      const filtered = value.filter(
        (v) => v !== "" && v !== null && v !== undefined
      );
      if (filtered.length > 0) {
        filteredParams[key] = filtered.join(",");
      } else {
        filteredParams[key] = "";
      }
    } else {
      // 单选字段
      filteredParams[key] = value;
    }
  });
  return filteredParams;
};

// 搜索操作
const handleSearch = () => {
  const filteredParams = filterParams();

  emit("update:modelValue", filteredParams);
  emit("search", filteredParams);
};

// 重置操作
const handleReset = () => {
  // 重置所有搜索参数
  Object.keys(searchParams).forEach((key) => {
    if (Array.isArray(searchParams[key])) {
      searchParams[key] = [""];
    } else {
      searchParams[key] = "";
    }
  });

  // 重置表单验证状态
  if (searchFormRef.value) {
    searchFormRef.value.resetFields();
  }

  loadSearchOptions();

  emit("update:modelValue", {});
  emit("reset");
};

// 导出操作
const handleExport = () => {
  const filteredParams = filterParams();
  // proxy.download(
  //   "biz/statistics/exportUserDetailStatistics",
  //   {
  //     ...filteredParams,
  //   },
  //   `${props.exportFileName}_${new Date().getTime()}.xlsx`
  // );
  emit("export", filteredParams);
};

// 获取搜索选项
const loadSearchOptions = async () => {
  const params = filterParams();

  try {
    const [
      gradeRes,
      universityRes,
      trainTypeRes,
      trainFieldRes,
      trainStatusRes,
      graduateStayRes,
      trainDeptRes,
    ] = await Promise.all([
      getGradeDropdown(params),
      getUniversityDropdown(params),
      getTrainTypeDropdown(params),
      getTrainFieldDropdown(params),
      getTrainStatusDropdown(params),
      getGraduateStayDropdown(params),
      getTrainDeptDropdown(params),
    ]);

    yearOptions.value = gradeRes.data || [];
    university.value = universityRes.data || [];
    training_category.value = trainTypeRes.data || [];
    specialty.value = trainFieldRes.data || [];
    train_progress.value = trainStatusRes.data || [];
    sys_yes_no.value = graduateStayRes.data || [];
    trainingUnitList.value = trainDeptRes.data || [];
  } catch (error) {
    console.error("获取搜索选项失败:", error);
    proxy.$modal.msgError("获取搜索选项失败");
  }
};

const handleChangeBlur = (key, options) => {
  console.log(key, options);
  loadSearchOptions();
};
const handleChange = (val, key, options) => {
  console.log(val, key, options);
  if (
    val.length === 0 ||
    val[val.length - 1] === "" ||
    (val.filter((v) => v !== "").length === options.length &&
      options.length > 1)
  ) {
    searchParams[key] = [""];
  } else {
    searchParams[key] = val.filter((v) => v !== "");
  }
};

// 初始化
onMounted(() => {
  loadSearchOptions();

  // 如果有初始值，设置到表单中
  if (props.modelValue && Object.keys(props.modelValue).length > 0) {
    Object.assign(searchParams, props.modelValue);
  }

  handleSearch();
});

// 暴露方法给父组件
defineExpose({
  handleSearch,
  handleReset,
  searchParams,
});
</script>

<style lang="scss" scoped>
.search-form {
  background: #fff;
  padding: 20px;
  border-radius: 4px;
  margin-bottom: 20px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  ::v-deep {
    .el-select,
    .el-input {
      width: 100%;
    }
  }

  .search-form-container {
    .el-form-item {
      margin-bottom: 16px;
    }
  }

  .search-buttons {
    text-align: left;

    .el-form-item {
      margin-bottom: 0;
    }
  }

  // 多选标签样式优化
  :deep(.el-select .el-select__tags) {
    max-width: calc(100% - 30px);
  }

  :deep(.el-tag) {
    max-width: 120px;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
  }
}
</style>
